﻿using System;
using System.Configuration;
using System.Linq;
using Microsoft.Practices.ServiceLocation;
using NBlock.Core;
using Cost.Models;
using System.Web.Security;

namespace Cost.Services
{
    public class nbUserService : IUserService
    {
        public IUserInfo GetUserInfo(string userId)
        {
            var repo = ServiceLocator.Current.GetInstance<ICostRepository<UserInfo>>();
            var user = repo.Find(userId);
            var orgRepo = ServiceLocator.Current.GetInstance<ICostRepository<Organization>>();
            var org = orgRepo.Find(user.OrgId);

            if (user != null)
            {
                return new nbUserInfo
                {
                    UserId = user.Id,
                    UserName = user.UserName,
                    OrgCode = user.OrgId,
                    OrgName = user.OrgName,
                    UnitCode = org.UnitId,
                    UnitName = org.UnitName,
                };
            }
            return null;
        }

        public bool HasRight(string userId, string privilegeId)
        {
            #region 判断是否为超级管理员
            var SuperAdminUserId = ConfigurationManager.AppSettings["SuperAdminUserId"];
            if (!string.IsNullOrWhiteSpace(SuperAdminUserId) && SuperAdminUserId.Equals(userId, StringComparison.CurrentCultureIgnoreCase))
            {
                return true;
            }
            #endregion

            #region 判断用户角色是否拥有此权限
            // 获取指定用户的所有角色
            var roles = ServiceLocator.Current.GetInstance<ICostRepository<UserRole>>()
                .FindAll(u => u.UserId == userId).Select(u => u.RoleId).ToArray();

            // 获取本节点及子节点的权限
            var childIds = GetPrivilegeIds(privilegeId);

            // 判断指定角色是否拥有该权限
            if (ServiceLocator.Current.GetInstance<ICostRepository<Permission>>()
                .IsExist(p => roles.Contains(p.MasterValue) && p.MasterType == "Role" && childIds.Contains(p.PrivilegeId)))
            {
                return true;
            }
            #endregion

            return false;
        }

        /// <summary>
        /// 获取本节点及子节点的权限
        /// </summary>
        /// <param name="parentId"></param>
        /// <returns></returns>
        private string[] GetPrivilegeIds(string parentId)
        {
            // TODO 需要缓存权限集合信息
            var privileges = ServiceLocator.Current.GetInstance<ICostRepository<Privilege>>().FindAll().ToList();
            var childIds = privileges.Where(p => p.FullPath.Contains(parentId)).Select(p => p.Id).ToArray();

            return childIds;
        }

        public bool IsInRole(string userId, string roleCode)
        {
            return ServiceLocator.Current.GetInstance<ICostRepository<UserRole>>()
                .IsExist(u => u.UserId == userId && u.RoleCode == roleCode);
        }

        public string ValidUser(string userCode, string password)
        {
            var repo = ServiceLocator.Current.GetInstance<ICostRepository<UserInfo>>();
            var user = repo.Find(u => u.UserCode == userCode);
            if (user != null)
            {
                if (user.Password == FormsAuthentication.HashPasswordForStoringInConfigFile(password, "md5"))
                {
                    return user.Id;
                }
                else
                {
                    return String.Empty;
                }
            }
            throw new Exception("用户名不存在!");
        }
    }
}
